跳到主要内容

JZ13 调整数组顺序使奇数位于偶数前面

https://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b

第一次解:

import java.util.*;


public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] reOrderArray (int[] array) {
if (array.length < 1) return array;
// 奇数
ArrayList<Integer> oddList = new ArrayList<>();
ArrayList<Integer> evenList = new ArrayList<>();
int[] result = new int[array.length];

for (int i = 0; i < array.length; i++) {
if ((array[i] & 1) == 1) {
oddList.add(array[i]);
} else {
evenList.add(array[i]);
}
}

for(int i = 0; i < oddList.size(); i++) {
result[i] = oddList.get(i);
}
int index = oddList.size();
for(int i = 0; i < evenList.size(); i++) {
result[index] = evenList.get(i);
index++;
}

return result;
}
}

第二次解:

其实没必要使用 ArrayList 来存,直接使用队列就行了

import java.util.*;


public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] reOrderArray (int[] array) {
if (array.length == 0) return array;
Queue<Integer> odd = new LinkedList<>();
Queue<Integer> even = new LinkedList<>();
int i = 0;
while (i < array.length) {
if (array[i] % 2 == 1) odd.add(array[i]);
else even.add(array[i]);
i++;
}
i = 0;
// 插入 odd
while (!odd.isEmpty()) {
array[i++] = odd.poll();
}
while (!even.isEmpty()) {
array[i++] = even.poll();
}

return array;
}
}